package lixp.rabbitmqAdvance.consumer.controller;

import lixp.rabbitmqAdvance.consumer.config.MessageConsumerHandler2;
import lixp.rabbitmqAdvance.consumer.service.QueueService;
import lixp.rabbitmqAdvance.consumer.utils.SpringUtil;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class ConsumerController {
    @Autowired
    private QueueService queueService;

    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Autowired
    MessageConsumerHandler2 messageConsumerHandler2;

    @GetMapping("add_new_listener")
    public String addNewListener(String queueName){
        //获取配置文件中配置的SimpleMessageListenerContainer对象
        SimpleMessageListenerContainer container = SpringUtil.getBean(SimpleMessageListenerContainer.class);
        List<String> queueNameList = queueService.getMQJSONArray();
        int count = 0;
        while(!queueNameList.contains(queueName)){
            queueNameList = queueService.getMQJSONArray();
            count++;
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(count >=5){
                return "动态添加监听失败";
            }
        }
        container.addQueueNames(queueName);
        long consumerCount = container.getActiveConsumerCount();
        return "修改成功:现有队列监听者["+consumerCount+"]个";
    }
//    可根据不同的情况创建不同的监听
//    @GetMapping("add_new_listener2")
//    public String addNewListener2(String queueName){
//        System.out.println("---->"+queueName);
//        SimpleMessageListenerContainer container = SpringUtil.getBean(SimpleMessageListenerContainer.class);
//        container.setMessageListener(messageConsumerHandler2);
//        container.addQueueNames(queueName);
//        long consumerCount = container.getActiveConsumerCount();
//        return "---->修改成功:现有队列监听者["+consumerCount+"]个";
//    }
}
